package handler

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "net/url"
    "os"
    "path"
    "path/filepath"
    "search-bycode/tools"
    "strconv"
    "strings"
    "time"

    "github.com/gin-gonic/gin"
)

type FileHandler struct {
}
type SearchQuery struct {
    Type     string `json:"type"`
    Size     string `json:"size"`
    Shape    string `json:"shape"`
    Material string `json:"material"`
    FileData string `json:"file"`
}

const OriginPath = "\\\\172.16.16.16\\车间\\写真图库\\"
const CustomShapePath = "\\\\172.16.16.16\\车间\\每日定做\\新零售BA定做\\"

const TMCustomShapePath = "\\\\172.16.16.16\\车间\\每日定做\\天猫店铺BD定做\\"

const PltPath = "\\\\172.16.16.16\\车间\\每日定做\\天猫店铺BD定做\\BD雕刻路径（勿动）\\"
const HostPic = "https://qiniu.honorjiahua.com/"

func (h *FileHandler) SearchFile(c *gin.Context) {

    var searchQuery SearchQuery
    searchQuery.Type = c.Query("type")
    searchQuery.Size = c.Query("size")
    searchQuery.Shape = c.Query("shape")
    searchQuery.Material = c.Query("material")

    err := c.ShouldBind(&searchQuery)
    if err != nil {
        log.Println(err)
    }
    var url string

    var ShapeNumber string
    if strings.Contains(searchQuery.Shape, "-") {
        ShapeNumber = strings.Split(searchQuery.Shape, "-")[0]
    }
    sizeList := strings.Split(searchQuery.Size, "*")
    var Name, TypeName string
    if searchQuery.Type == "AA" {
        Name = searchQuery.Type + "-" + searchQuery.Material
        TypeName = tools.ShapeDict[Name]
    } else {
        TypeName = tools.ShapeDict[strings.ReplaceAll(searchQuery.Type, " ", "")]
    }

    if len(sizeList) < 2 {
        log.Println("err sizeList数组越界")
    }
    sizeName := sizeList[0] + "x" + sizeList[1]
    if strings.Contains(searchQuery.Shape, "-L") || strings.Contains(searchQuery.Shape, "-Y") || strings.Contains(searchQuery.Shape, "-S") ||
        strings.Contains(searchQuery.Shape, "-H2") || strings.Contains(searchQuery.Shape, "-H") {
        url = OriginPath + TypeName + `\` + sizeName + `\` + ShapeNumber + ".jpg"
    } else {
        url = OriginPath + TypeName + `\` + sizeName + `\` + searchQuery.Shape + ".jpg"
    }
    if TypeName == "WDD" {
        url = OriginPath + TypeName + `\` + searchQuery.Shape + `\` + searchQuery.Shape + `-` + sizeName + ".jpg"
    }
    //过滤文件不存在的数据
    _, err = os.Stat(url)
    log.Println(url)
    // 判断文件夹是否存在
    if err == nil {
        log.Printf("文件夹 %s 存在\n", url)
        c.JSON(http.StatusOK, gin.H{"status": 200, "message": "存在"})
        return
    } else if os.IsNotExist(err) {
        fmt.Printf("文件夹 %s 不存在\n", url)
        c.JSON(http.StatusOK, gin.H{"status": 400, "message": "不存在"})
        return
    } else {
        fmt.Printf("无法确定文件夹 %s 是否存在： %v\n", url, err)
        c.JSON(http.StatusOK, gin.H{"status": 400, "message": "不存在"})
        return
    }
}

func (h *FileHandler) UploadCustom(c *gin.Context) {
    c.Request.URL.RawQuery = strings.ReplaceAll(c.Request.URL.RawQuery, "+", "%2B")
    // 获取上传的文件
    var searchQuery SearchQuery
    var err error
    goodsId := c.Query("goodsId")
    outerId := c.Query("outerId")
    c.ShouldBindJSON(&searchQuery)
    file := tools.TrimBase64Header(searchQuery.FileData)
    suffix := c.Query("suffix")
    //_, outerId := getDirOrMk(searchQuery)
    if goodsId == "" && suffix == "" {
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "请求失败",
            "error":  "缺少必要参数",
        })
        return
    }
    if strings.Index(suffix, ".") == -1 {
        suffix = "." + suffix
    }
    now := time.Now()
    //filename := now.UnixMilli()
    if err != nil {
    }
    outIds := strings.Split(outerId, "+")

    var paths string
    if outIds[0] == "BD" {
        pathPre := TMCustomShapePath + strconv.Itoa(int(now.Month())) +
            "月\\" + strconv.Itoa(int(now.Month())) + "." + strconv.Itoa(now.Day()) + "日\\"
        paths = pathPre + goodsId + suffix
        if err = os.MkdirAll(filepath.Dir(paths), 0750); err != nil {
            c.JSON(200, gin.H{
                "status": "500",
                "error":  err.Error(),
            })
            return
        }
        originPltFile := PltPath + outIds[1] + ".plt"
        newPltfile := pathPre + goodsId + ".plt"
        // 打开源文件
        tools.Copy(originPltFile, newPltfile)
    } else {
        // CustomShapePath
        paths = CustomShapePath + strconv.Itoa(int(now.Month())) +
            "月\\" + strconv.Itoa(int(now.Month())) + "." + strconv.Itoa(now.Day()) + "日\\" + goodsId + suffix
        if err = os.MkdirAll(filepath.Dir(paths), 0750); err != nil {
            c.JSON(200, gin.H{
                "status": "500",
                "error":  err.Error(),
            })
            return
        }
    }
    //_ = file
    err = tools.Base64ToFile(file, paths)
    if err != nil {
        c.JSON(200, gin.H{
            "status": "500",
            "error":  err.Error(),
        })
        return
    }
    c.JSON(200, gin.H{
        "status": "200",
    })
}

func (h *FileHandler) UploadPic(c *gin.Context) {
    goodsId := c.Query("goodsId")
    picHost := c.Query("host")
    picUrl := c.Query("url")
    now := time.Now()
    var fileName string
    if goodsId != "" {
        fileName = goodsId + ".jpg"
        if picHost == "" {
            picHost = HostPic
        }
        picUrl = picHost + goodsId + ".jpg"
    }
    if picUrl != "" {
        fileName = path.Base(picUrl)
    }
    if picUrl == "" && goodsId == "" {
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "请求失败",
            "error":  "缺少必要参数",
        })
        return
    }

    resp, err := http.Get(picUrl)
    parsedURL, err := url.Parse(picUrl)
    if err != nil {
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "请求失败",
            "error":  "缺少必要参数",
        })
        return
    }
    defer resp.Body.Close()
    fileName = tools.GetDownloadFilename(resp, parsedURL)
    if err != nil {
        //panic(err)
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "下载失败",
            "error":  "下载失败:" + err.Error(),
        })
        return
    }

    paths := CustomShapePath + strconv.Itoa(int(now.Month())) +
        "月\\" + strconv.Itoa(int(now.Month())) + "." + strconv.Itoa(now.Day()) + "日\\" + fileName

    // 创建文件
    file, err := os.Create(paths)
    if err != nil {
        //panic(err)
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "保存失败",
            "error":  "保存错误:" + err.Error(),
        })
        return
    }
    defer file.Close()

    // 将 HTTP 响应的 body 写入到文件
    _, err = io.Copy(file, resp.Body)
    if err != nil {
        //panic(err)
        c.JSON(200, gin.H{
            "status": 500,
            "msg":    "保存失败",
            "error":  "保存错误:" + err.Error(),
        })
        return
    }
    c.JSON(200, gin.H{
        "status": 200,
        "msg":    "成功",
        "error":  "",
    })

}
